﻿using System.Text;
using System.Net;
using System.Net.Sockets;

namespace Coding4Fun.PrinterDisplayHack
{
    public class SendToPrinter
    {
        public string Host { get; set; }

        public int Send(string message)
        {
            IPEndPoint endPoint = null;

            try
            {
                IPAddress addr = Dns.GetHostAddresses(Host)[0];

                endPoint = new IPEndPoint(addr, 9100);
            }
            catch
            {
                return 1;
            }

            const string startPJLSequence = "\u001B%-12345X@PJL RDYMSG DISPLAY = \"";
            const string endPJLSequence = "\"\r\n\u001B%-12345X\r\n";

            ASCIIEncoding encoding = new ASCIIEncoding();

            try
            {
                Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

                sock.Connect(endPoint);

                sock.Send(encoding.GetBytes(startPJLSequence));
                sock.Send(encoding.GetBytes(message));
                sock.Send(encoding.GetBytes(endPJLSequence));

                sock.Close();
            }
            catch
            {
                return 1;
            }

            return 0;
        }
    }
}
